package szf.im.route.util;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author shizhanfu
 */
@Component
public class ZkClient {
    private volatile CuratorFramework client;
    @Autowired
    private Config cfg;

    @PostConstruct
    public void init() {
        if (client == null) {
            synchronized (ZkClient.class) {
                if (client == null) {
                    RetryPolicy rp = new RetryNTimes(10, 10000);
                    client = CuratorFrameworkFactory.builder().connectString(cfg.getZkUrl())
                            .connectionTimeoutMs(1000).retryPolicy(rp).build();
                    client.start();
                }
            }
        }
    }

    /**
     * @return 随机server连接
     * @throws Exception
     */
    public String getBalanceServer() throws Exception {
        List<String> servers;
        servers = client.getChildren().forPath("/im");
        Random rd = new Random();
        int i = rd.nextInt(servers.size());
        return new String(client.getData().forPath("/im/" + servers.get(i)));
    }
}
